package com.ketangpai.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ketangpai.admin.dao.UserDao;
import com.ketangpai.admin.entity.User;
import com.ketangpai.admin.exception.BusinessException;
import com.ketangpai.admin.mapper.UserMapper;
import com.ketangpai.admin.service.UserService;
import com.ketangpai.admin.utils.Encrypt;
import com.ketangpai.admin.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.regex.Pattern;

@Service

public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private UserDao userDao;
    /**
     * 登录
     */

    @Override
    public User findByUsername(String username) {
        User user =  userMapper.findByUserName(username);
        return user;
    }

    @Override
    public User findByPhone(String phone) {

        return userMapper.findByPhone(phone);
    }

    /**
     * 注册
     *
     * @return
     */
    @Override
    public boolean register(User user) throws Exception {
        //解密
        //加密
        System.out.println(user.getPassword());
        user.setPassword(Encrypt.AESDecrypt(user.getPassword()));
//        System.out.println("-----------------------------------"+user.getAccount()+user.getPassword());
        String md5String = Md5Util.getMD5String(user.getPassword());
        //添加
//        System.out.println("-----------------------------------"+user.getAccount()+md5String);
        user.setPassword(md5String);
        System.out.println(user);
        try {
            userMapper.add(user);
            return true;
        } catch (Exception e) {
            return false;

        }

    }

    @Override
    public User selectById(Integer id) {
        return userDao.selectById(id);
    }

    /**
     * 手机号校验
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (phoneNumber.length() == 11)) {
            return !Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return true;
    }

    @Override
    public User selectByAccount(String account) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("account",account);
        User user = userDao.selectOne(wrapper);
        if(user==null){
            throw new BusinessException("找不到用户");
        }
        return user;
    }

    @Override
    public boolean update(User user) {
        return userDao.updateById(user) > 0;
    }

}
